package com.bw.mvvm

import android.os.Bundle
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.bw.mvvm.mvvm.PostState
import com.bw.mvvm.mvvm.PostViewModel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

/**
 * okhttp+retrofit+协程+flow+livedata
 *
 * mvvm:
 * view:持有viewmodel
 * model:
 * viewModel:viewModel不持有view
 *
 * 3.数据传递：ViewModel通过LiveData或Flow给View
 *
 *
 */
class MainActivity : AppCompatActivity() {
    private val mPostViewModel: PostViewModel by lazy{
        ViewModelProvider(this)[PostViewModel::class.java]
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        //1：view通知viewModel请求数据
        mPostViewModel.getPostList(1,20)
        mPostViewModel.getPostList2(1,20)
        //3：通过LiveDaya订阅数据
        mPostViewModel.mPostLiveData_.observe(this){it->
            Toast.makeText(this,it.size.toString(),Toast.LENGTH_SHORT).show()
        }
        //通过stateflow流订阅数据，根据不同状态更新UI
        lifecycleScope.launch{
            mPostViewModel.mPostStateFlow_.collect{it->
                when(it){
                    is PostState.Error->{
                        Toast.makeText(this@MainActivity,it.error,Toast.LENGTH_SHORT).show()
                    }
                    is PostState.Success->{
                        Toast.makeText(this@MainActivity,it.data.size.toString(),Toast.LENGTH_SHORT).show()
                    }
                    is PostState.Loading->{
                        Toast.makeText(this@MainActivity,"加载中",Toast.LENGTH_SHORT).show()
                    }
                    is PostState.Empty->{
                        Toast.makeText(this@MainActivity,"空数据",Toast.LENGTH_SHORT).show()
                    }
                }

            }
        }

    }
}